package xian.woniuxy.b_realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;

/**
 * @author gao
 * @time 2021/12/23 11:51:04
 */
public class App {
    public static void main(String[] args) {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        // ====================================================================

        // 使用自定义Realm
        Realm realm = new MyRealm();

        // ====================================================================
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        String username = "foo";
        String password = "123";
        // 认证
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        System.out.println("认证前身份:" + subject.getPrincipal());

        try {
            // 一旦调用subject.login()方法，就会回调Realm的doGetAuthenticationInfo方法
            subject.login(token);
            System.out.println("认证通过");
        } catch (Exception e) {
            System.out.println("认证失败:" + e);
        }

        System.out.println("认证后身份:" + subject.getPrincipal());

        // 授权， 前提是要先通过认证！
        // 一旦调用了 subject.isPermitted()方法，shrio就会回调MyRealm中的doGetAuthorizationInfo方法
        System.out.println("user:save " + subject.isPermitted("user:save"));
        System.out.println("user:delete " + subject.isPermitted("user:delete"));
        System.out.println("user:update " + subject.isPermitted("user:update"));
        System.out.println("user:find " + subject.isPermitted("user:find"));
    }
}
